package edu.zut.main.socket;

import java.io.*;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class SocketDemo2 {
    public static void main(String[] args) {
        File file = new File("C:\\Users\\xueyin\\Desktop\\Redis.docx");
        System.out.println(file.exists());
    }

}

//文件或图片上传(一对一，实际一对多（多线程控制）)
class FileClient{
    public static void main(String[] args) throws IOException {

        Socket socket = new Socket(InetAddress.getByName("127.0.0.1"), 8888);
        System.out.println("客户端连接成功");
        //将本地的一个文件上传到服务器
        FileInputStream is = new FileInputStream(new File("C:\\Users\\xueyin\\Desktop\\Redis.docx"));
        BufferedInputStream bis = new BufferedInputStream(is);
        //基于socket的输出流
        BufferedOutputStream bos = new BufferedOutputStream(socket.getOutputStream());

        byte[] buffer = new byte[1024];
        int len;
        //一边读本地文件，一边写到服务器
        while ((len = bis.read(buffer)) != -1){
            bos.write(buffer,0,len);
            bos.flush();
        }
        System.out.println("上传完毕");
        bos.close();
        bis.close();
        socket.close();
    }
}


class FileServer{

    public static void main(String[] args) throws IOException {

        ServerSocket serverSocket = new ServerSocket(8888);
        //监听客户端请求
        Socket socket = serverSocket.accept();
        System.out.println("连接成功.......");

        //读取客户端上传的文件，并将其保存
        BufferedInputStream bis = new BufferedInputStream(socket.getInputStream());

        BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File("./redis.docx")));

        byte[] buffer = new byte[1024];
        int len;
        while ((len = bis.read(buffer)) != -1){
            bos.write(buffer,0,len);
            bos.flush();
        }

        bos.close();
        bis.close();
        socket.close();
        serverSocket.close();

    }

}


